"use client";

import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import { useAuth } from './AuthContext';
import { Product } from '@/types/Product';
import * as api from '@/lib/api'; // Import all functions from api

export interface CartItem extends Product {
    quantity: number;
}

interface CartContextType {
    cartItems: CartItem[];
    addToCart: (product: Product, quantity: number) => Promise<void>;
    updateQuantity: (productId: string, quantity: number) => Promise<void>;
    removeFromCart: (productId: string) => Promise<void>;
    clearCart: () => Promise<void>;
    loading: boolean;
    error: string | null;
    itemCount: number;
}

const CartContext = createContext<CartContextType | undefined>(undefined);

export const CartProvider = ({ children }: { children: ReactNode }) => {
    const { isAuthenticated } = useAuth();
    const [cartItems, setCartItems] = useState<CartItem[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const fetchCart = useCallback(async () => {
        if (!isAuthenticated) {
            setLoading(false);
            setCartItems([]);
            return;
        }
        setLoading(true);
        setError(null);
        try {
            const cart = await api.getCart();
            setCartItems(cart.items || []);
        } catch (err: any) {
            if (err.response && err.response.status === 404) {
                setCartItems([]); // Cart doesn't exist, so it's empty
            } else {
                setError('Failed to fetch cart');
                console.error(err);
            }
        } finally {
            setLoading(false);
        }
    }, [isAuthenticated]);

    useEffect(() => {
        fetchCart();
    }, [fetchCart]);

    const handleApiCall = async (apiCall: () => Promise<any>) => {
        if (!isAuthenticated) {
            const err = "You must be logged in to perform this action.";
            setError(err);
            throw new Error(err);
        }
        try {
            await apiCall();
            await fetchCart();
        } catch (err: any) {
            setError(err.message || 'An unexpected error occurred.');
            throw err;
        }
    };

    const addToCart = (product: Product, quantity: number) => 
        handleApiCall(() => api.addToCart(product.id, quantity));

    const updateQuantity = (productId: string, quantity: number) =>
        handleApiCall(() => api.updateCartItemQuantity(productId, quantity));

    const removeFromCart = (productId: string) => 
        handleApiCall(() => api.removeFromCart(productId));

    const clearCart = () => handleApiCall(api.clearCart);

    const itemCount = cartItems.reduce((total, item) => total + item.quantity, 0);

    return (
        <CartContext.Provider value={{ cartItems, addToCart, updateQuantity, removeFromCart, clearCart, loading, error, itemCount }}>
            {children}
        </CartContext.Provider>
    );
};

export const useCart = () => {
    const context = useContext(CartContext);
    if (context === undefined) {
        throw new Error('useCart must be used within a CartProvider');
    }
    return context;
}; 